<?php
/**
 * 添加门禁设备管理菜单
 */

// MySQL连接配置
$host = '113.44.136.17';
$port = '3306';
$database = 'qiandao';
$username = 'qiandao';
$password = 'NGbks3HWx5PhSxDX';

try {
    $pdo = new PDO("mysql:host={$host};port={$port};dbname={$database};charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "=== 添加门禁设备管理菜单 ===\n\n";
    
    // 查找打卡积分的一级菜单ID
    $stmt = $pdo->query("SELECT id FROM system_menu WHERE title = '打卡积分' AND pid = 0");
    $parentMenu = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$parentMenu) {
        echo "❌ 未找到'打卡积分'一级菜单，请先运行菜单初始化脚本\n";
        exit(1);
    }
    
    $pid1 = $parentMenu['id'];
    echo "✓ 找到打卡积分菜单 (ID: {$pid1})\n";
    
    // 检查是否已存在设备管理菜单
    $stmt = $pdo->prepare("SELECT id FROM system_menu WHERE title = '设备管理' AND pid = ?");
    $stmt->execute([$pid1]);
    $existingMenu = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($existingMenu) {
        echo "⚠️  设备管理菜单已存在 (ID: {$existingMenu['id']})，先删除旧菜单\n";
        
        // 删除旧的设备管理相关菜单
        $stmt = $pdo->prepare("DELETE FROM system_menu WHERE (title LIKE '%设备%' OR node LIKE 'checkin/device%') AND pid IN (SELECT id FROM (SELECT id FROM system_menu WHERE pid = ?) t)");
        $stmt->execute([$pid1]);
        
        $stmt = $pdo->prepare("DELETE FROM system_menu WHERE title = '设备管理' AND pid = ?");
        $stmt->execute([$pid1]);
        
        echo "✓ 已删除旧的设备管理菜单\n";
    }
    
    // 插入二级菜单：设备管理
    $stmt = $pdo->prepare("INSERT INTO system_menu (pid, title, icon, node, url, params, target, sort, status, create_at) VALUES (?, '设备管理', '', '', '#', '', '_self', 70, 1, NOW())");
    $stmt->execute([$pid1]);
    $pid2_device = $pdo->lastInsertId();
    echo "✓ 插入二级菜单：设备管理 (ID: {$pid2_device})\n";
    
    // 插入三级菜单：设备列表
    $stmt = $pdo->prepare("INSERT INTO system_menu (pid, title, icon, node, url, params, target, sort, status, create_at) VALUES (?, '设备列表', 'layui-icon layui-icon-component', 'checkin/device/index', '', '', '_self', 100, 1, NOW())");
    $stmt->execute([$pid2_device]);
    echo "✓ 插入三级菜单：设备列表\n";
    
    // 插入三级菜单：设备统计
    $stmt = $pdo->prepare("INSERT INTO system_menu (pid, title, icon, node, url, params, target, sort, status, create_at) VALUES (?, '设备统计', 'layui-icon layui-icon-chart', 'checkin/device/statistics', '', '', '_self', 90, 1, NOW())");
    $stmt->execute([$pid2_device]);
    echo "✓ 插入三级菜单：设备统计\n";
    
    echo "\n✅ 门禁设备管理菜单添加成功！\n";
    echo "\n菜单结构：\n";
    echo "  打卡积分\n";
    echo "    └── 设备管理\n";
    echo "        ├── 设备列表 (checkin/device/index)\n";
    echo "        └── 设备统计 (checkin/device/statistics)\n";
    echo "\n请刷新浏览器查看新菜单。\n";
    
} catch (PDOException $e) {
    echo "❌ 数据库错误: " . $e->getMessage() . "\n";
    exit(1);
}
?>
